﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Diagnostics;


namespace CommunicationManagementBusinessLayer
{

    /// <summary>
    /// Summary description for PDFCreateFromImages
    /// </summary>
    public class PDFCreateFromImages
    {
        public PDFCreateFromImages()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        /// <summary>
        /// this function will merge more than one pdf file and return array with all merged
        /// </summary>
        /// <param name="strFiles">streams containing files</param>
        /// <param name="btFile">return array</param>
        /// <returns>true for succeed , false for error</returns>
        public static bool MergePdf(Stream[] strFiles, ref byte[] btFile)
        {



            string outFileNameString = "";
            if (strFiles.Length < 2) return false;
            try
            {
                //string outFile = strFiles[strFiles.Length - 1];
                iTextSharp.text.Document document = null;
                PdfCopy writer = null;
                int n = 0;
                
                for (int i = 0; i < strFiles.Length - 1; i++)
                {
                    byte[] btReader = new byte[strFiles[i].Length];
                    try { strFiles[i].Seek(0, SeekOrigin.Begin); }
                    catch { }
                    strFiles[i].Read(btReader, 0, btReader.Length);

                    PdfReader reader = new PdfReader(btReader);
                    n = reader.NumberOfPages;
                    if (i == 0)
                    {
                        document = new iTextSharp.text.Document(reader.GetPageSizeWithRotation(1));
                        
                        try
                        {
                            string str = Path.GetTempFileName();
                            if (File.Exists(str))
                                File.Delete(str);

                            outFileNameString = str;
                            

                          

                        }
                        catch
                        {
                        }


                        
                        writer = new PdfCopy(document, new System.IO.FileStream(outFileNameString, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite));
                        document.Open();
                    }
                    PdfImportedPage page;
                    for (int j = 1; j <= n; j++)
                    {
                        page = writer.GetImportedPage(reader, j);
                        writer.AddPage(page);

                    }
                    PRAcroForm form = reader.AcroForm;
                    if (form != null)
                    {
                        writer.CopyAcroForm(reader);
                    }

                }
                
                


               

                document.Close();


                

                btFile = File.ReadAllBytes(outFileNameString);

                try { File.Delete(outFileNameString); }
                catch { }
               

            }
            catch (Exception ex)
            {
                ex.ToString();
                return false;
            }
            return true;
        }


        /// <summary>
        /// this function will create a pdf file and return its byte [] from images entered
        /// </summary>
        /// <param name="lstImages">the images to create file from</param>
        /// <returns>a byte array contains file</returns>
        public static byte[] createFile(List<System.Drawing.Image> lstImages)
        {
            iTextSharp.text.Document doc1 = new iTextSharp.text.Document(PageSize.A4, 0, 0, 0, 0);
            //string strFileName = Path.GetTempFileName();
            //if (File.Exists(strFileName))
            //{
            //    try
            //    {
            //        File.Delete(strFileName);
            //    }
            //    catch
            //    {
            //    }
            //}

            
            string outFileNameString = Path.GetTempFileName();
            if (File.Exists(outFileNameString))
                try { File.Delete(outFileNameString); }
                catch { }

            PdfWriter.GetInstance(doc1, new System.IO.FileStream(outFileNameString, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite));
            doc1.Open();

            for (int i = 0; i < lstImages.Count; i++)
            {
                lstImages[i] = getResizedImage(PageSize.A4, lstImages[i]);
                MemoryStream ms = new MemoryStream();
                lstImages[i].Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] btInstImage = ms.ToArray();

               
                Image current = Image.GetInstance(btInstImage);
               
                doc1.Add(current);

                ms.Close();
            }

            if (lstImages.Count == 0)
            {
                
                doc1.Add(new Paragraph("Error no data to print"));

            }

            doc1.Close();



            byte[] btRet = File.ReadAllBytes(outFileNameString);
            if (File.Exists(outFileNameString))
                try { File.Delete(outFileNameString); }
                catch { }


            //try { allDoc.Seek(0, SeekOrigin.Begin); }
            //catch { }
            //allDoc.Read(btRet, 0, btRet.Length);
            //allDoc.Close();

            return btRet;


        }

        public static byte[] createBarcodeFile(List<System.Drawing.Image> lstImages,System.Drawing.Rectangle rect,bool print)
        {
            iTextSharp.text.Document doc1 = new iTextSharp.text.Document(new Rectangle(rect.Width, rect.Height), 0, 0, 0, 0);
            //string strFileName = Path.GetTempFileName();
            //if (File.Exists(strFileName))
            //{
            //    try
            //    {
            //        File.Delete(strFileName);
            //    }
            //    catch
            //    {
            //    }
            //}

            
            string outFileNameString = Path.GetTempFileName();
            if (File.Exists(outFileNameString))
                try { File.Delete(outFileNameString); }
                catch { }
         PdfWriter writer=   PdfWriter.GetInstance(doc1, new System.IO.FileStream(outFileNameString, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite));
            doc1.Open();

            for (int i = 0; i < lstImages.Count; i++)
            {
                //lstImages[i] = getResizedImage(new Rectangle(0, 0, 150, 30), lstImages[i]);
                MemoryStream ms = new MemoryStream();
                lstImages[i].Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] btInstImage = ms.ToArray();
                
                Image current = Image.GetInstance(btInstImage);

                doc1.Add(current);

                ms.Close();
            }

            PdfAction jAction = PdfAction.JavaScript(@"this.print({
bUI: true,
bSilent: false,
bShrinkToFit: true
});", writer);
            //PdfAction jAction2 = PdfAction.JavaScript("window.close();\r", writer);

            if (print)
            {
                writer.AddJavaScript(jAction);
            }
            if (lstImages.Count == 0)
            {

                doc1.Add(new Paragraph("Error no data to print"));

            }

            doc1.Close();

            byte[] btRet = File.ReadAllBytes(outFileNameString);
            if (File.Exists(outFileNameString))
                try { File.Delete(outFileNameString); }
                catch { }

            return btRet;


        }

        /// <summary>
        /// this function will resize image by rectangle
        /// </summary>
        /// <param name="rect">the rectangle to resize by</param>
        /// <param name="img">the img to resize</param>
        /// <returns>the resized image</returns>
        public static System.Drawing.Image getResizedImage(Rectangle rect, System.Drawing.Image img)
        {
            int width = (int)rect.Width;//(int)(img.HorizontalResolution * (rect.Width/72));
            int height = (int)rect.Height;//(int)(img.VerticalResolution * (rect.Height/72));

            int newWidth,newHeight;
            newWidth = width;
            newHeight = (int)(img.Height * (float)newWidth / img.Width);
            if (newHeight > height)
            {
                newHeight = height;
                newWidth = (int)(img.Width * (float)newHeight / img.Height);


            }


            System.Drawing.Image newImage = new System.Drawing.Bitmap(img, new System.Drawing.Size(newWidth, newHeight));

            return newImage;

        }


    }



}